package com.pureut.order.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.order.domain.CustomerManagement;
import com.pureut.order.domain.SalesOrder;
import com.pureut.order.domain.SalesOrderDetail;
import com.pureut.order.dto.SalesOrderDetailDto;
import com.pureut.order.dto.SalesOrderDto;
import com.pureut.order.dto.SalesOrderViewDto;
import com.pureut.order.mapper.SalesOrderDetailMapper;
import com.pureut.order.mapper.SalesOrderMapper;
import com.pureut.order.service.CustomerManagementService;
import com.pureut.order.service.SalesOrderDetailService;
import com.pureut.order.service.SalesOrderService;
import com.pureut.order.vo.*;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.OrderFeignService;
import com.pureut.system.api.SchedulingPlanFeignService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.SalesMaterialDataVo;
import com.pureut.system.api.vo.SchedulingPlanVo;
import com.pureut.system.api.vo.SysWorkbenchAuditAgentVo;
import com.pureut.system.api.vo.UpdateDataBySchedulingVo;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/***
 *
 * Author:C
 * Date:2022/11/30 17:57
 * @DESC
 */
@Service
public class SalesOrderServiceImpl extends ServiceImpl<SalesOrderMapper, SalesOrder> implements SalesOrderService {


    @Resource
    SalesOrderMapper salesOrderMapper;

    @Resource
    FeignService feignService;

    @Resource
    OrderFeignService orderFeignService;

    @Resource
    SchedulingPlanFeignService schedulingPlanFeignService;

    @Lazy
    @Resource
    SalesOrderDetailService salesOrderDetailService;

    @Lazy
    @Resource
    SalesOrderDetailMapper salesOrderDetailMapper;

    @Resource
    CustomerManagementService customerManagementService;


    /**
     * 销售订单列表
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<SalesOrderDto> getList(SalesOrderVo salesOrderVo) {
        //销售订单列表
        List<SalesOrderDto> salesOrderList = salesOrderMapper.getSalesOrderList(salesOrderVo);
        //获取销售订单状态缓存字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("sales_order_status");
        Map<String, String> actualMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取销售订单类型缓存字典数据
        List<SysDictData> arrayList = DictUtils.getDictCache("sales_order_type");
        Map<String, String> arrayMap = arrayList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单位
        List<SysDictData> unit = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unit.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取销售订单优先级缓存字典数据
        List<SysDictData> arrayPriorityList = DictUtils.getDictCache("sales_order_priority");
        Map<String, String> priorityMap = arrayPriorityList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (SalesOrderDto entity : salesOrderList) {
            //单位
            entity.setMaterialUnitDict(unitMap.get(entity.getMaterialUnit()));
            //获取销售订单状态缓存字典数据
            entity.setStatusDict(actualMap.get(entity.getStatus()));
            //获取销售订单类型缓存字典数据
            entity.setOrderTypeDict(arrayMap.get(entity.getOrderType()));
            //获取销售订单优先级缓存字典数据
            entity.setOrderPriorityDict(priorityMap.get(entity.getOrderPriority()));
            //归属人
            String userName = feignService.getUserName(Long.valueOf(entity.getAttributor()));
            entity.setAttributor(userName);
        }
        return salesOrderList;
    }

    /**
     * 新增销售订单
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addSalesOrder(SalesOrderVo salesOrderVo) throws Exception {
        //保存销售订单
        SalesOrder salesOrder = new SalesOrder();
        BeanUtils.copyProperties(salesOrderVo, salesOrder);
        String authorityCoding = feignService.getAuthorityCoding("order:saleOrder:list");
        if (authorityCoding == null) {
            throw new GlobalException("未进行单据配置,单据编码生成失败");
        }
        salesOrder.setAttributor(salesOrderVo.getAttributor())
                .setDeptId(SecurityUtils.getDeptId())
                .setCreateBy(SecurityUtils.getUsername())
                .setCreateTime(new Date())
                .setStatus(1)
                .setSalesOrderNum(authorityCoding);
        boolean save = save(salesOrder);
        //保存销售订单明细信息
        List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
        try {
            if (save) {
                List<SalesOrderDetailDto> detailList = salesOrderVo.getSalesOrderDetailList();
                if (detailList != null && detailList.size() > 0) {
                    for (SalesOrderDetailDto entity : detailList) {
                        SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
                        BeanUtils.copyProperties(entity, salesOrderDetail);
                        salesOrderDetail
                                .setCreateBy(SecurityUtils.getUsername())
                                .setNumberRolls(Integer.parseInt(entity.getNumberRolls()))
                                .setDeviation(Integer.parseInt(entity.getDeviation()))
                                .setCreateTime(new Date())
                                .setOrderDetailStatus(1)
                                .setSalesOrderId(salesOrder.getId())
                                .setQualityStandard(Integer.parseInt(entity.getQualityStandard()))
                                .setPacking(Integer.parseInt(entity.getPacking()));
                        salesOrderDetailList.add(salesOrderDetail);
                    }
                }
                return salesOrderDetailService.saveBatch(salesOrderDetailList);
            } else {
                throw new GlobalException("保存失败");
            }
        } catch (Exception e) {
            throw new SQLException("批量保存失败");
        }
    }

    /**
     * 提交评审
     *
     * @param id
     * @return
     */
    @Override
    public boolean submitReview(Long id) {
        SalesOrder salesOrder = getById(id);
        if (salesOrder.getStatus() == 1) {
            salesOrder.setStatus(2);
            updateById(salesOrder);
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, id));
            List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
            for (SalesOrderDetail entity : salesOrderDetails) {
                entity.setOrderDetailStatus(2);
                salesOrderDetailList.add(entity);
            }

            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
            sysWorkbenchAuditAgentVo.setDocConfig("order:sale:saleOrder:examine");
            sysWorkbenchAuditAgentVo.setReceiptName("销售订单");
            sysWorkbenchAuditAgentVo.setReceiptNumber(salesOrder.getSalesOrderNum());//
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

            return salesOrderDetailService.updateBatchById(salesOrderDetailList);
        } else {
            throw new GlobalException("只能对待提交的订单进行操作");
        }

    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteReview(Long id) {
        SalesOrder salesOrder = getById(id);
        if (2 == salesOrder.getStatus()) {
            salesOrder.setStatus(1);
            updateById(salesOrder);
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, id));
            List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
            for (SalesOrderDetail entity : salesOrderDetails) {
                if (entity.getOrderDetailStatus() == 2) {
                    entity.setOrderDetailStatus(1);
                    salesOrderDetailList.add(entity);
                }
            }

            feignService.deleteDoc(salesOrder.getSalesOrderNum(), "销售订单");
            return salesOrderDetailService.updateBatchById(salesOrderDetailList);
        } else {
            throw new GlobalException("只能撤销待审核的销售订单");
        }
    }

    /**
     * 手动关结
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean close(SalesOrderVo salesOrderVo) {
        SalesOrder salesOrder = getById(salesOrderVo.getId());
        if (salesOrder.getStatus() == 6 || salesOrder.getStatus() == 7) {
            throw new GlobalException("不能操作已完成、已关节的单据");
        }
        salesOrder.setStatus(7);
        salesOrder.setCloseReason(salesOrderVo.getCloseReason());
        //销售订单关结时，需要校验销售订单下的明细状态，只有明细状态全为“已完成”或“已终止”时才允许进行关结，关结后单据状态更新为“已关结”，明细状态不变
        List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        boolean isAll = true;
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (entity.getOrderDetailStatus() != 6 || entity.getOrderDetailStatus() != 8) {
                isAll = false;
                break;
            }
        }
        if (isAll) {
            return updateById(salesOrder);
        } else {
            throw new GlobalException("明细状态全为“已完成”或“已终止”时才允许进行关结该单据");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        if (idList.size() > 0) {
            List<SalesOrder> salesOrders = new ArrayList<>();
            List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
            //获取销售订单列表
            List<SalesOrder> salesOrderList = salesOrderMapper.selectList(new QueryWrapper<SalesOrder>().lambda().in(SalesOrder::getId, idList));
            for (SalesOrder entity : salesOrderList) {
                boolean status = 1 == entity.getStatus();
                if (status) {
                    salesOrders.add(entity);

                    feignService.deleteDoc(entity.getSalesOrderNum(), "销售订单");

                } else {
                    throw new GlobalException("只能删除待提交的订单");
                }
            }
            //判断是否存在明细数据以及状态是否为待提交或者未通过
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().in(SalesOrderDetail::getSalesOrderId, idList));
            for (SalesOrderDetail salesOrderDetail : salesOrderDetails) {
                boolean status = 1 == salesOrderDetail.getOrderDetailStatus() || 5 == salesOrderDetail.getOrderDetailStatus();
                if (status) {
                    salesOrderDetailList.add(salesOrderDetail);
                }
            }
            if (salesOrders.size() > 0 && salesOrderDetailList.size() > 0) {
                removeByIds(salesOrders);
                return salesOrderDetailService.removeByIds(salesOrderDetailList);
            } else {
                throw new GlobalException("没有满足删除条件的订单");
            }
        }
        return false;
    }

    /**
     * 修改销售订单
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSalesOrder(SalesOrderVo salesOrderVo) throws SQLException {
        //获取销售订单
        SalesOrder salesOrder = getById(salesOrderVo.getId());
        //判断单据状态进行修改
        if (1 == salesOrder.getStatus()) {
            //修改销售订单
            BeanUtils.copyProperties(salesOrderVo, salesOrder);
            updateById(salesOrder);
            //修改销售订单明细
            List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
            boolean b = salesOrderDetailService.removeByIds(salesOrderDetails);
            //保存销售订单明细信息
            List<SalesOrderDetail> salesOrderDetailList = new ArrayList<>();
            try {
                if (b) {
                    List<SalesOrderDetailDto> detailList = salesOrderVo.getSalesOrderDetailList();
                    if (detailList != null && detailList.size() > 0) {
                        for (SalesOrderDetailDto entity : detailList) {
                            SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
                            BeanUtils.copyProperties(entity, salesOrderDetail);
                            salesOrderDetail.setCreateBy(SecurityUtils.getUsername())
                                    .setNumberRolls(Integer.parseInt(entity.getNumberRolls()))
                                    .setDeviation(Integer.parseInt(entity.getDeviation()))
                                    .setCreateTime(new Date())
                                    .setOrderDetailStatus(1)
                                    .setSalesOrderId(salesOrder.getId())
                                    .setQualityStandard(Integer.parseInt(entity.getQualityStandard()))
                                    .setPacking(Integer.parseInt(entity.getPacking()));
                            salesOrderDetailList.add(salesOrderDetail);

                            //修改审核代办状态为已处理
                            feignService.updateStatus(3, entity.getSalesOrderNum(), "销售订单");//


                        }
                    }
                    return salesOrderDetailService.saveBatch(salesOrderDetailList);
                } else {
                    throw new GlobalException("保存失败");
                }
            } catch (Exception e) {
                throw new SQLException("批量保存失败");
            }
        } else {
            throw new GlobalException("只能修改待提交的数据");
        }
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public SalesOrderViewDto getView(Long id) {
        SalesOrderViewDto salesOrderViewDto = new SalesOrderViewDto();
        //获取销售订单信息
        SalesOrder salesOrder = getById(id);
        BeanUtils.copyProperties(salesOrder, salesOrderViewDto);
        //归属人
        String userName = feignService.getUserName(Long.valueOf(salesOrder.getAttributor()));
        salesOrderViewDto.setAttributor(userName);
        salesOrderViewDto.setUserId(salesOrder.getAttributor());
        //获取客户信息
        CustomerManagement byId = customerManagementService.getById(salesOrderViewDto.getCustomerId());
        salesOrderViewDto.setCustomerName(byId.getCustomerName());
        salesOrderViewDto.setCustomerCode(byId.getCustomerNum());
        //获取订单类别字典值
        List<SysDictData> typeArray = DictUtils.getDictCache("sales_order_type");
        Map<String, String> orderTypeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        salesOrderViewDto.setOrderTypeDict(orderTypeMap.get(String.valueOf(salesOrder.getOrderType())));
        salesOrderViewDto.setOrderType(String.valueOf(salesOrder.getOrderType()));
        //获取订单优先级字典值
        List<SysDictData> priorityArray = DictUtils.getDictCache("sales_order_priority");
        Map<String, String> orderpriorityArrayMap = priorityArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        salesOrderViewDto.setOrderPriorityDict(orderpriorityArrayMap.get(String.valueOf(salesOrder.getOrderPriority())));
        salesOrderViewDto.setOrderPriority(String.valueOf(salesOrder.getOrderPriority()));
        //获取销售订单明细列表
        List<SalesOrderDetailDto> detailList = salesOrderDetailMapper.getDetailList(id);
        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取铺网类型标准缓存字典数据
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取包装字典值
        List<SysDictData> packArray = DictUtils.getDictCache("sale_order_packing");
        Map<String, String> orderPackMap = packArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //偏差
        List<SysDictData> deviationArray = DictUtils.getDictCache("sale_order_deviation");
        Map<String, String> deviationMap = deviationArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //纸管卷数
        List<SysDictData> rollsArray = DictUtils.getDictCache("sale_order_deviation");
        Map<String, String> rollsMap = rollsArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取质量标准字典值
        List<SysDictData> standardArray = DictUtils.getDictCache("sale_order_quality_standard");
        Map<String, String> orderStandardArrayPackMap = standardArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (SalesOrderDetailDto entity : detailList) {
            entity.setMaterialNetTypeDict(netTypeMap.get(String.valueOf(entity.getMaterialNetType())));
            entity.setMaterialNetDict(netMap.get(String.valueOf(entity.getMaterialNet())));
            //获取包装字典值
            entity.setQualityStandard(entity.getQualityStandard());
            entity.setQualityStandardDict(orderStandardArrayPackMap.get(entity.getQualityStandard()));
            //获取质量标准字典值
            entity.setPacking(entity.getPacking());
            entity.setPackingDict(orderPackMap.get(entity.getPacking()));
            //偏差
            entity.setDeviation(entity.getDeviation());
            entity.setDeviationDict(deviationMap.get(entity.getDeviation()));
            //纸管卷数
            entity.setNumberRolls(entity.getNumberRolls());
            entity.setNumberRollsDict(rollsMap.get(entity.getNumberRolls()));
        }
        salesOrderViewDto.setSalesOrderDetailList(detailList);
        return salesOrderViewDto;
    }

    /**
     * 合同上传
     *
     * @param contractUploadVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean contractUpload(ContractUploadVo contractUploadVo) throws Exception {
        SalesOrder salesOrder = getById(contractUploadVo.getId());
        //获取包装字典值
        List<SysDictData> packArray = DictUtils.getDictCache("sale_order_packing");
        Map<String, String> orderPackMap = packArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        if (4 == salesOrder.getStatus()) {
            salesOrder.setContractUrl(contractUploadVo.getContractUrl());
            salesOrder.setSalesContractNum(contractUploadVo.getSalesContractNum());
            salesOrder.setStatus(5);
            updateById(salesOrder);
            //新增排程计划数据
            List<SchedulingPlanVo> schedulingPlanVoList = new ArrayList<>();
            //获取明细数据
            List<SalesOrderDetailDto> detailList = salesOrderDetailMapper.getDetailList(contractUploadVo.getId());

            List<Long> ids = new ArrayList<>();
            for (SalesOrderDetailDto entity : detailList) {
                ids.add(entity.getId());
            }
            List<SalesOrderDetail> salesOrderDetailList1 = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().in(SalesOrderDetail::getId, ids));
            List<SalesOrderDetail> salesOrderDetails = new ArrayList<>();
            for (SalesOrderDetail entity : salesOrderDetailList1) {
                entity.setOrderDetailStatus(9);
                salesOrderDetails.add(entity);
            }
            boolean b = salesOrderDetailService.updateBatchById(salesOrderDetails);

            for (SalesOrderDetailDto entity : detailList) {
                if (entity.getMaterialCategory() == 4) {
                    SchedulingPlanVo schedulingPlanVo = new SchedulingPlanVo();
                    schedulingPlanVo.setPlanId(contractUploadVo.getId());
                    schedulingPlanVo.setPlanNote(salesOrder.getRemark());
                    schedulingPlanVo.setPlanType(1);
                    CustomerManagement customerManagement = customerManagementService.getById(salesOrder.getCustomerId());
                    schedulingPlanVo.setPlanCustomerCode(customerManagement.getCustomerNum());
                    schedulingPlanVo.setPlanCustomerName(customerManagement.getCustomerName());
                    schedulingPlanVo.setPlanContractWeight(Double.parseDouble(entity.getPlanWeight()));
                    schedulingPlanVo.setPlanDeliveryTime(entity.getDeliveryDate());
                    schedulingPlanVo.setPlanTheContract(salesOrder.getSalesContractNum());
                    schedulingPlanVo.setPlanMaterialId(entity.getMaterialId());
                    schedulingPlanVo.setPlanAssociatedId(salesOrder.getId());
                    schedulingPlanVo.setPlanAssociatedCode(salesOrder.getSalesOrderNum());
                    schedulingPlanVo.setWidthCloth(entity.getWidthCloth());
                    schedulingPlanVo.setThickness(entity.getThickness());
                    schedulingPlanVo.setRollDiameter(entity.getRollDiameter());
                    schedulingPlanVo.setPacking(Integer.parseInt(entity.getPacking()));
                    schedulingPlanVo.setPackingDict(orderPackMap.get(String.valueOf(entity.getPacking())));
                    schedulingPlanVo.setNumberRolls(Integer.parseInt(entity.getNumberRolls()));
                    schedulingPlanVo.setMaterialRatio(entity.getMaterialRatio());
                    schedulingPlanVo.setOrderRemark(salesOrder.getRemark());
                    schedulingPlanVo.setPlanMaterialName(entity.getMaterialName());
                    schedulingPlanVo.setPlanMaterialCode(entity.getMaterialCode());
                    schedulingPlanVo.setPlanMaterialSpec(entity.getMaterialSpec());
                    schedulingPlanVo.setGramWeight(entity.getMaterialGheavy());
                    schedulingPlanVo.setPlanPath(salesOrder.getContractUrl());
                    if (entity.getMaterialNet() != null) {
                        schedulingPlanVo.setMaterialNet(Integer.parseInt(entity.getMaterialNet()));
                    }
                    if (entity.getMaterialNetType() != null) {
                        schedulingPlanVo.setMaterialNetType(Integer.parseInt(entity.getMaterialNetType()));
                    }
                    schedulingPlanVoList.add(schedulingPlanVo);
                }
            }
            if (schedulingPlanVoList.size() > 0) {
                AjaxResult add = schedulingPlanFeignService.addPlan(schedulingPlanVoList);
                String code = add.get("code").toString();
                return "200".equals(code);
            }
            return b;
        } else {
            throw new GlobalException("只能对待签订的订单进行上传");
        }
    }

    /**
     * 销售订单审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saleOrderReview(OrderReviewVo orderReviewVo) {

        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectOne(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getId, orderReviewVo.getId()));
        //获取销售订单数据
        SalesOrder salesOrder1 = getById(salesOrderDetail.getSalesOrderId());
        if (salesOrderDetail.getOrderDetailStatus() == 2 || salesOrderDetail.getOrderDetailStatus() == 3) {
            String perms = "order:sale:saleOrder:examine";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = salesOrder1.getSalesOrderNum() + salesOrderDetail.getId();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 2, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                //同意审核
                if (data == 1) {
                    salesOrderDetail.setOrderDetailStatus(4);
                    //获取订单信息
                    SalesOrder salesOrder = getById(salesOrderDetail.getSalesOrderId());
                    if (salesOrder.getReviewBy() == null) {
                        salesOrder.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        salesOrder.setReviewBy(salesOrder.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    salesOrder.setReviewTime(new Date());
                    int i = salesOrderDetailMapper.updateById(salesOrderDetail);
                    //获取明细列表，判断每一条的状态
                    List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrderDetail.getSalesOrderId()));
                    boolean isTrue = true;
                    for (SalesOrderDetail entity : salesOrderDetailList) {
                        if (entity.getOrderDetailStatus() != 4) {
                            isTrue = false;
                            break;
                        }
                    }
                    if (isTrue) {
                        salesOrder.setStatus(4);
                    } else {
                        salesOrder.setStatus(3);
                    }
                    updateById(salesOrder);

                    feignService.updateStatus(3, salesOrder.getSalesOrderNum(), "销售订单");

                    return i > 0;
                } else if (data == 2) {
                    salesOrderDetail.setOrderDetailStatus(3);
                    //获取订单信息
                    SalesOrder salesOrder = getById(salesOrderDetail.getSalesOrderId());
                    if (salesOrder.getReviewBy() == null) {
                        salesOrder.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        salesOrder.setReviewBy(salesOrder.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    salesOrder.setReviewTime(new Date());
                    salesOrder.setStatus(3);
                    salesOrderDetailMapper.updateById(salesOrderDetail);
                    return updateById(salesOrder);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    salesOrderDetail.setOrderDetailStatus(5);
                    //获取订单信息
                    SalesOrder salesOrder = getById(salesOrderDetail.getSalesOrderId());
                    if (salesOrder.getReviewBy() == null) {
                        salesOrder.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        salesOrder.setReviewBy(salesOrder.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    salesOrder.setStatus(3);
                    salesOrder.setReviewTime(new Date());
                    salesOrderDetailMapper.updateById(salesOrderDetail);

                    SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
                    sysWorkbenchAuditAgentVo.setDocConfig("order:sale:saleOrder:examine");
                    sysWorkbenchAuditAgentVo.setReceiptName("销售订单");
                    sysWorkbenchAuditAgentVo.setReceiptNumber(salesOrder.getSalesOrderNum());//
                    sysWorkbenchAuditAgentVo.setStatus(2);//待处理
                    sysWorkbenchAuditAgentVo.setReceiptContent("有单据未通过,请及时查看");
                    sysWorkbenchAuditAgentVo.setPassFlag("1");
                    sysWorkbenchAuditAgentVo.setCreateName(salesOrder.getCreateBy());

                    feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);
                    return updateById(salesOrder);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }
    }

    /**
     * 获取销售订单列表(其他模块调用)
     *
     * @param salesOrderVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<SalesOrderDto> getSaleOrderList(SalesOrderVo salesOrderVo) {
        //销售订单列表
        List<SalesOrderDto> salesOrderList = salesOrderMapper.getOrderSalesOrderList(salesOrderVo);
        //获取销售订单状态缓存字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("sales_order_status");
        Map<String, String> actualMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取销售订单类型缓存字典数据
        List<SysDictData> arrayList = DictUtils.getDictCache("sales_order_type");
        Map<String, String> arrayMap = arrayList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单位
        List<SysDictData> unit = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unit.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取销售订单优先级缓存字典数据
        List<SysDictData> arrayPriorityList = DictUtils.getDictCache("sales_order_priority");
        Map<String, String> priorityMap = arrayPriorityList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (SalesOrderDto entity : salesOrderList) {
            //单位
            entity.setMaterialUnitDict(unitMap.get(entity.getMaterialUnit()));
            //获取销售订单状态缓存字典数据
            entity.setStatusDict(actualMap.get(entity.getStatus()));
            //获取销售订单类型缓存字典数据
            entity.setOrderTypeDict(arrayMap.get(entity.getOrderType()));
            //获取销售订单优先级缓存字典数据
            entity.setOrderPriorityDict(priorityMap.get(entity.getOrderPriority()));
            //归属人
            String userName = feignService.getUserName(Long.valueOf(entity.getAttributor()));
            entity.setAttributor(userName);
        }
        return salesOrderList;
    }

    /**
     * 排程模块回传数据，修改销售订单状态及数据（feign调用）
     *
     * @param updateDataBySchedulingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDataByScheduling(UpdateDataBySchedulingVo updateDataBySchedulingVo) {
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, updateDataBySchedulingVo.getSalesOrderNum()));
        //根据销售订单号获取明细
        List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        //获取回传列表
        List<SalesMaterialDataVo> materialList = updateDataBySchedulingVo.getMaterialList();

        for (SalesOrderDetail entity1 : salesOrderDetailList) {
            for (SalesMaterialDataVo entity2 : materialList) {
                if (entity1.getMaterialCode().equals(entity2.getMaterialCode())) {
                    entity1.setProducedWeight(entity2.getProducedWeight());
                    entity1.setNoProducedWeight(entity2.getNoProducedWeight());
                    entity1.setShippingWeight(entity2.getShippingWeight());
                    entity1.setBackWeight(entity2.getBackWeight());
                    entity1.setOrderDetailStatus(entity2.getStatus());
                }
            }
        }
        //修改明细
        boolean b = salesOrderDetailService.updateBatchById(salesOrderDetailList);
        if (b) {
            boolean isAll = true;
            for (SalesOrderDetail entity : salesOrderDetailList) {
                if (entity.getOrderDetailStatus() != 8) {
                    isAll = false;
                    break;
                }
            }
            //如果修改之后明细都为已经完成，就修改销售订单状态为已完成
            if (isAll) {
                salesOrder.setStatus(6);
                return updateById(salesOrder);
            }
        }
        return b;
    }

    /**
     * 根据销售订单号及物料编码获取明细信息
     *
     * @param saleNumber
     * @param materialCode
     * @return
     */
    @Override
    public SalesOrderDetailDto getDataBySaleNumberAndMaterialCode(String saleNumber, String materialCode) {
        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取铺网类型标准缓存字典数据
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取采购计划质量标准
        List<SysDictData> standardArray = DictUtils.getDictCache("quality_standard");
        Map<String, String> standardMap = standardArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取销售订单
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, saleNumber));
        //获取明细
        List<SalesOrderDetailDto> detailList = salesOrderDetailMapper.getDetailList(salesOrder.getId());
        SalesOrderDetailDto salesOrderDetailDto = new SalesOrderDetailDto();
        for (SalesOrderDetailDto entity : detailList) {
            if (entity.getMaterialCode().equals(materialCode)) {
                BeanUtils.copyProperties(entity, salesOrderDetailDto);
            }
        }
        salesOrderDetailDto.setMaterialNetTypeDict(netTypeMap.get(salesOrderDetailDto.getMaterialNetType()));
        salesOrderDetailDto.setMaterialNetDict(netMap.get(salesOrderDetailDto.getMaterialNet()));
        salesOrderDetailDto.setQualityStandardDict(standardMap.get(salesOrderDetailDto.getQualityStandard()));
        return salesOrderDetailDto;
    }

    /**
     * 根据销售订单修改对应明细状态（生产计划 feign调用）
     *
     * @param updateSaleOrderDetailStatusVo
     */
    @Override
    public void updateSaleOrderDetailStatus(UpdateSaleOrderDetailStatusVo updateSaleOrderDetailStatusVo) {
        //获取销售订单
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, updateSaleOrderDetailStatusVo.getSaleOrderNo()));

        List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        for (SalesOrderDetail entity : salesOrderDetailList) {
            if (entity.getMaterialCode().equals(updateSaleOrderDetailStatusVo.getMaterialCode())) {
                entity.setOrderDetailStatus(updateSaleOrderDetailStatusVo.getStatus());
                salesOrderDetailService.updateById(entity);
            }
        }

        SaleDocumentVo saleDocumentVo = new SaleDocumentVo();
        saleDocumentVo.setSaleId(salesOrder.getId());
        updateSaleDocument(saleDocumentVo);

    }

    /**
     * 成品称重页面回传数据至销售订单(成品称重 feign调用)
     *
     * @param backDataVo
     */
    @Override
    public void backData(BackDataVo backDataVo) {
        //根据销售订单号获取明细
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, backDataVo.getSaleNumber()));
        List<SalesOrderDetail> salesOrderDetailList = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));


        for (SalesOrderDetail entity : salesOrderDetailList) {
            if (entity.getMaterialCode().equals(backDataVo.getMaterialCode())) {
                //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                if (entity.getProducedWeight() == null || "0".equals(entity.getProducedWeight()) || "".equals(entity.getProducedWeight())) {
                    entity.setProducedWeight(String.valueOf(backDataVo.getNetWeight()));
                    //如果第一次生产就生产量大于等于计划量
                    if(backDataVo.getNetWeight() >= Double.parseDouble(entity.getPlanWeight())){
                        //将未生产重量归零
                        entity.setNoProducedWeight("0");
                        //明细改为完成
                        entity.setOrderDetailStatus(8);
                    }
                    BigDecimal subtract1 = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(String.valueOf(backDataVo.getNetWeight())));
                    BigDecimal subtract2 = subtract1.subtract(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                    if(Double.parseDouble(subtract2.toString()) < 0){
                        entity.setNoProducedWeight("0");
                    }else {
                        entity.setNoProducedWeight(subtract2.toString());
                    }
                } else {
                    //先将重量相加
                    BigDecimal add = new BigDecimal(entity.getProducedWeight()).add(new BigDecimal(String.valueOf(backDataVo.getNetWeight())));
                    String planWeight = entity.getPlanWeight();
                    //判断已生产量和计划量大小
                    if (Double.parseDouble(add.toString()) >= Double.parseDouble(planWeight)) {
                        //将未生产重量归零
                        entity.setNoProducedWeight("0");
                        //明细改为完成
                        entity.setOrderDetailStatus(8);
                        entity.setProducedWeight(add.toString());
                    }else {
                        entity.setProducedWeight(add.toString());
                        BigDecimal subtract1 = new BigDecimal(entity.getPlanWeight()).subtract(add);
                        BigDecimal subtract2 = subtract1.subtract(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                        if(Double.parseDouble(subtract2.toString()) < 0){
                            entity.setNoProducedWeight("0");
                        }else {
                            entity.setNoProducedWeight(subtract2.toString());
                        }

                    }
                }
                salesOrderDetailService.updateById(entity);
            }
        }
    }

    /**
     * 销售发货回传发货重量
     *
     * @param backDataVo
     */
    @Override
    public boolean updateShippingWeight(BackDataVo backDataVo) {

        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getShippingWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getShippingWeight();
        }


        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(backDataVo.getNetWeight());

        BigDecimal add1 = shippingBig.add(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));

        return salesOrderMapper.updateShippingWeight(backDataVo) > 0;
    }

    /**
     * 销售发货重量回传扣减
     *
     * @param backDataVo
     */
    @Override
    public boolean updateShippingWeightSub(BackDataVo backDataVo) {
        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getShippingWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getShippingWeight();
        }

        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(backDataVo.getNetWeight());

        BigDecimal add1 = shippingBig.subtract(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));

        return salesOrderMapper.updateShippingWeight(backDataVo) > 0;
    }

    /**
     * 销售退货重量回传（）
     *
     * @param backDataVo
     * @return
     */
    @Override
    public boolean updateShippingOutWeight(BackDataVo backDataVo) {
        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getBackWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getBackWeight();
        }


        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(backDataVo.getNetWeight());

        BigDecimal add1 = shippingBig.add(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));

        return salesOrderMapper.updateShippingOutWeight(backDataVo);
    }

    /**
     * 销售发货扣除
     *
     * @param backDataVo
     * @return
     */
    @Override
    public boolean updateShippingWeightSubBack(BackDataVo backDataVo) {
        SalesOrderDetail salesOrderDetail = salesOrderDetailMapper.selectShipping(backDataVo);

        String shippingWeight = "0";
        if (salesOrderDetail.getBackWeight() != null) {

            //取出销售订单的发货重量
            shippingWeight = salesOrderDetail.getBackWeight();
        }

        BigDecimal shippingBig = new BigDecimal(shippingWeight);

        BigDecimal add = new BigDecimal(backDataVo.getNetWeight());

        BigDecimal add1 = shippingBig.subtract(add);

        backDataVo.setNetWeight(Double.parseDouble(add1.toString()));

        return salesOrderMapper.updateShippingOutWeight(backDataVo);
    }

    /**
     * 委外入库回传销售订单明细委外重量(委外入库fegin调用)
     *
     * @param backDataVo
     * @return
     */
    @Override
    public boolean updateSubWeight(BackDataVo backDataVo) {
        //获取销售订单数据
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, backDataVo.getSaleNumber()));
        //获取该销售订单下的明细数据
        List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (backDataVo.getMaterialCode().equals(entity.getMaterialCode())) {
                if (entity.getSubcontractWeight() == 0) {
                    BigDecimal subtract;
                    //委外重量
                    entity.setSubcontractWeight(backDataVo.getNetWeight());
                    //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                    if (entity.getProducedWeight() == null) {
                        entity.setProducedWeight("0");
                        BigDecimal subtract1 = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                        entity.setNoProducedWeight(subtract1.toString());
                    } else {
                        subtract = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(entity.getProducedWeight()));
                        BigDecimal subtract1 = subtract.subtract(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                        if (Double.parseDouble(subtract1.toString()) < 0) {
                            entity.setNoProducedWeight("0");
                            entity.setOrderDetailStatus(8);
                        } else {
                            entity.setNoProducedWeight(subtract1.toString());
                        }
                    }
                } else {
                    BigDecimal add = new BigDecimal(String.valueOf(backDataVo.getNetWeight())).add(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                    entity.setSubcontractWeight(Double.parseDouble(String.valueOf(add.toString())));
                    BigDecimal subtract1;
                    //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                    if (entity.getProducedWeight() == null) {
                        entity.setProducedWeight("0");
                        subtract1 = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                        entity.setNoProducedWeight(subtract1.toString());
                    } else {
                        subtract1 = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(entity.getProducedWeight()));
                        BigDecimal subtract2 = subtract1.subtract(new BigDecimal(String.valueOf(entity.getSubcontractWeight())));
                        if (Double.parseDouble(subtract2.toString()) < 0) {
                            entity.setNoProducedWeight("0");
                            entity.setOrderDetailStatus(8);
                        } else {
                            entity.setNoProducedWeight(subtract2.toString());
                        }
                    }
                }
            }
        }
        salesOrderDetailService.updateBatchById(salesOrderDetails);
        //如果全部都为已完成就将单据修改为已完成
        boolean isTrue = true;
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (entity.getOrderDetailStatus() != 8) {
                isTrue = false;
                break;
            }
        }
        if (isTrue) {
            salesOrder.setStatus(6);
        }

        //销售订单明细状态是否为关结或者终止，改销售订单状态
        SaleDocumentVo saleDocumentVo = new SaleDocumentVo();
        saleDocumentVo.setSaleId(salesOrder.getId());
        updateSaleDocument(saleDocumentVo);

        return updateById(salesOrder);
    }

    /**
     * 委外入库扣减销售订单明细委外重量(委外入库fegin调用)
     *
     * @param backDataVo
     * @return
     */
    @Override
    public boolean updateSubWeightDelete(BackDataVo backDataVo) {
        //获取销售订单数据
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, backDataVo.getSaleNumber()));
        //获取该销售订单下的明细数据
        List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, salesOrder.getId()));
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (backDataVo.getMaterialCode().equals(entity.getMaterialCode())) {
                if (entity.getSubcontractWeight() != 0) {

                    BigDecimal add = new BigDecimal(String.valueOf(entity.getSubcontractWeight())).subtract(new BigDecimal(String.valueOf(backDataVo.getNetWeight())));
                    entity.setSubcontractWeight(Double.parseDouble(String.valueOf(add.toString())));
                    //未生产重量 = 计划重量 - 已生产重量 - 委外重量
                    if (entity.getProducedWeight() == null) {
                        entity.setProducedWeight("0");
                    }
                    BigDecimal subtract = new BigDecimal(entity.getPlanWeight()).subtract(new BigDecimal(entity.getProducedWeight()));
                    BigDecimal subtract1 = subtract.subtract(new BigDecimal(String.valueOf(add.toString())));
                    if (Double.parseDouble(subtract1.toString()) < 0) {
                        entity.setNoProducedWeight("0");
                        entity.setOrderDetailStatus(8);
                    } else {
                        entity.setNoProducedWeight(subtract1.toString());
                    }
                }
            }
        }
        salesOrderDetailService.updateBatchById(salesOrderDetails);
        //如果全部都为已完成就将单据修改为已完成
        boolean isTrue = true;
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (entity.getOrderDetailStatus() != 8) {
                isTrue = false;
                break;
            }
        }
        if (isTrue) {
            salesOrder.setStatus(6);
        }

        //销售订单明细状态是否为关结或者终止，改销售订单状态
        SaleDocumentVo saleDocumentVo = new SaleDocumentVo();
        saleDocumentVo.setSaleId(salesOrder.getId());
        updateSaleDocument(saleDocumentVo);

        return updateById(salesOrder);
    }

    /**
     * 销售订单状态回传
     *
     * @param backDataVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSaleStatus(BackDataVo backDataVo) {

//        boolean flag = salesOrderDetailMapper.updateSaleStatus(backDataVo);

        //通过销售订单号查出销售id
        SalesOrder salesOrder = salesOrderMapper.selectOne(new QueryWrapper<SalesOrder>().lambda().eq(SalesOrder::getSalesOrderNum, backDataVo.getSaleNumber()));

        SaleDocumentVo saleDocumentVo = new SaleDocumentVo();
        saleDocumentVo.setSaleId(salesOrder.getId());
        saleDocumentVo.setMaterialCode(backDataVo.getMaterialCode());
        return updateSaleDocument(saleDocumentVo);
    }


    /**
     * 判断销售订单的明细状态，同步修改销售订单的状态
     *
     * @param saleDocumentVo
     * @return
     */
    @Override
    public boolean updateSaleDocument(SaleDocumentVo saleDocumentVo) {
        List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.selectList(new QueryWrapper<SalesOrderDetail>().lambda().eq(SalesOrderDetail::getSalesOrderId, saleDocumentVo.getSaleId()));
        for (SalesOrderDetail entity : salesOrderDetails) {
            if (entity.getMaterialCode().equals(saleDocumentVo.getMaterialCode())) {
                entity.setOrderDetailStatus(8);
            }
        }
        //修改明细状态为已完成
        salesOrderDetailService.updateBatchById(salesOrderDetails);

        //如果一部分是完成一部分是终止
        int num = 0;

        //如果全为完成
        int finish = 0;

        //如果全为已经终止
        int termination = 0;

        for (SalesOrderDetail salesOrderDetail : salesOrderDetails) {
            if (salesOrderDetail.getOrderDetailStatus() == 6 || salesOrderDetail.getOrderDetailStatus() == 8) {
                num++;
                if (salesOrderDetail.getOrderDetailStatus() == 6) {
                    termination++;
                }

                if (salesOrderDetail.getOrderDetailStatus() == 8) {
                    finish++;
                }

            }
        }

        //查出销售订单
        SalesOrder salesOrder = salesOrderMapper.selectById(saleDocumentVo.getSaleId());

        //如果是明细全部为已经完成，则修改单据状态为已经完成
        // 如果一部分为完成,一部分为终止,则修改单据状态为已完成
        if (finish == salesOrderDetails.size() || num == salesOrderDetails.size()) {
            salesOrder.setStatus(6);
        }
        //如果全部为已经终止,则改状态为已关结
        if (termination == salesOrderDetails.size()) {
            salesOrder.setStatus(7);
        }

        return updateById(salesOrder);
    }


}
